package com.tree.backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tree.backend.entity.dto.OrderQueryDTO;
import com.tree.backend.entity.pojo.Demand;
import com.tree.backend.mapper.DemandOrderMapper;
import com.tree.backend.entity.pojo.DemandOrder;
import com.tree.backend.entity.pojo.User;
import com.tree.backend.entity.vo.OrderListVO;
import com.tree.backend.entity.vo.OrderVO;
import com.tree.backend.service.IDemandOrderService;
import com.tree.backend.service.IDemandService;
import com.tree.backend.service.IUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Objects;

/**
 * 需求订单服务实现类
 * @author tree
 */
@Service
@RequiredArgsConstructor
public class DemandOrderServiceImpl extends ServiceImpl<DemandOrderMapper, DemandOrder> implements IDemandOrderService {
    
    private final IDemandService demandService;
    private final IUserService userService;
    private final DemandOrderMapper demandOrderMapper;
    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    
    @Override
    public IPage<OrderListVO> getOrderList(OrderQueryDTO queryDTO) {
        // 创建分页对象
        Page<DemandOrder> page = new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize());
        
        // 创建查询条件
        QueryWrapper<DemandOrder> queryWrapper = new QueryWrapper<>();
        // 必须按企业ID筛选
        queryWrapper.eq("enterprise_id", queryDTO.getEnterpriseId());
        
        // 执行分页查询
        Page<DemandOrder> orderPage = demandOrderMapper.selectPage(page, queryWrapper);
        
        // 转换为VO对象
        return orderPage.convert(this::convertToOrderListVO);
    }
    
    @Override
    public OrderVO getOrderDetail(Long orderId, Long enterpriseId) {
        // 查询订单信息
        DemandOrder demandOrder = demandOrderMapper.selectById(orderId);
        if (demandOrder == null) {
            throw new RuntimeException("订单不存在");
        }
        
        // 验证企业权限
        if (!Objects.equals(demandOrder.getEnterpriseId(), enterpriseId)) {
            throw new RuntimeException("无权限访问该订单");
        }
        
        // 转换为VO对象
        return convertToOrderVO(demandOrder);
    }
    
    @Override
    @Transactional
    public void finishOrder(Long orderId, Long enterpriseId) {
        // 查询订单信息
        DemandOrder demandOrder = demandOrderMapper.selectById(orderId);
        if (demandOrder == null) {
            throw new RuntimeException("订单不存在");
        }
        
        // 验证企业权限
        if (!Objects.equals(demandOrder.getEnterpriseId(), enterpriseId)) {
            throw new RuntimeException("无权限操作该订单");
        }
        
        // 设置完成时间和状态
        demandOrder.setFinishTime(LocalDateTime.now());
        demandOrderMapper.updateById(demandOrder);
        
        // 更新需求状态为已完成（状态6）
        Demand demand = demandService.getById(demandOrder.getDemandId());
        if (demand != null) {
            demand.setStatus(6);
            demandService.updateById(demand);
        }
    }
    
    @Override
    public IPage<OrderListVO> searchOrders(OrderQueryDTO queryDTO) {
        // 创建分页对象
        Page<DemandOrder> page = new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize());
        
        // 创建查询条件
        QueryWrapper<DemandOrder> queryWrapper = new QueryWrapper<>();
        // 必须按企业ID筛选
        queryWrapper.eq("enterprise_id", queryDTO.getEnterpriseId());
        
        // 搜索条件
        if (queryDTO.getTitle() != null && !queryDTO.getTitle().isEmpty()) {
            // 由于标题和用户名在其他表，需要使用子查询或者联表查询
            // 这里简化处理，先查询出符合条件的订单ID
            // 实际项目中可能需要使用联表查询
        }
        
        // 执行分页查询
        Page<DemandOrder> orderPage = demandOrderMapper.selectPage(page, queryWrapper);
        
        // 转换为VO对象
        return orderPage.convert(this::convertToOrderListVO);
    }
    
    /**
     * 将DemandOrder转换为OrderListVO
     */
    private OrderListVO convertToOrderListVO(DemandOrder demandOrder) {
        OrderListVO orderListVO = new OrderListVO();
        
        // 设置订单基本信息
        orderListVO.setId(demandOrder.getId());
        orderListVO.setDemandId(demandOrder.getDemandId());
        orderListVO.setEnterpriseId(demandOrder.getEnterpriseId());
        orderListVO.setUserId(demandOrder.getUserId());
        orderListVO.setBidAmount(demandOrder.getBidAmount());
        // 根据finishTime是否为null判断状态
        orderListVO.setStatus(demandOrder.getFinishTime() != null ? 1 : 0);
        
        // 设置时间信息
        if (demandOrder.getConfirmTime() != null) {
            orderListVO.setConfirmTime(demandOrder.getConfirmTime().format(DATE_TIME_FORMATTER));
        }
        if (demandOrder.getFinishTime() != null) {
            orderListVO.setFinishTime(demandOrder.getFinishTime().format(DATE_TIME_FORMATTER));
        }
        if (demandOrder.getCreateTime() != null) {
            orderListVO.setCreateTime(demandOrder.getCreateTime().format(DATE_TIME_FORMATTER));
        }
        if (demandOrder.getUpdateTime() != null) {
            orderListVO.setUpdateTime(demandOrder.getUpdateTime().format(DATE_TIME_FORMATTER));
        }
        
        // 填充需求信息
        Demand demand = demandService.getById(demandOrder.getDemandId());
        if (demand != null) {
            orderListVO.setDemandTitle(demand.getTitle());
            orderListVO.setDemandDescription(demand.getDescription());
        }
        
        // 填充用户信息
        User user = userService.getById(demandOrder.getUserId());
        if (user != null) {
            orderListVO.setUsername(user.getUsername());
        }
        
        return orderListVO;
    }
    
    /**
     * 将DemandOrder转换为OrderVO
     */
    private OrderVO convertToOrderVO(DemandOrder demandOrder) {
        OrderVO orderVO = new OrderVO();
        
        // 设置订单基本信息
        orderVO.setId(demandOrder.getId());
        orderVO.setDemandId(demandOrder.getDemandId());
        orderVO.setEnterpriseId(demandOrder.getEnterpriseId());
        orderVO.setUserId(demandOrder.getUserId());
        orderVO.setBidAmount(demandOrder.getBidAmount());
        orderVO.setDescription(demandOrder.getDescription());
        // 根据finishTime是否为null判断状态
        orderVO.setStatus(demandOrder.getFinishTime() != null ? 1 : 0);
        
        // 设置时间信息
        if (demandOrder.getConfirmTime() != null) {
            orderVO.setConfirmTime(demandOrder.getConfirmTime().format(DATE_TIME_FORMATTER));
        }
        if (demandOrder.getFinishTime() != null) {
            orderVO.setFinishTime(demandOrder.getFinishTime().format(DATE_TIME_FORMATTER));
        }
        if (demandOrder.getCreateTime() != null) {
            orderVO.setCreateTime(demandOrder.getCreateTime().format(DATE_TIME_FORMATTER));
        }
        if (demandOrder.getUpdateTime() != null) {
            orderVO.setUpdateTime(demandOrder.getUpdateTime().format(DATE_TIME_FORMATTER));
        }
        
        // 填充需求信息
        Demand demand = demandService.getById(demandOrder.getDemandId());
        if (demand != null) {
            orderVO.setDemandTitle(demand.getTitle());
            orderVO.setDemandDescription(demand.getDescription());
        }
        
        // 填充用户信息
        User user = userService.getById(demandOrder.getUserId());
        if (user != null) {
            orderVO.setUsername(user.getUsername());
        }
        
        return orderVO;
    }
}
